
import AMap from 'AMap'

export const geolocation = (options = {}) => {
  return new Promise((resolve, reject) => {
    AMap.plugin('AMap.Geolocation', function() {
      var geolocation = new AMap.Geolocation({
        // 是否使用高精度定位，默认：true
        enableHighAccuracy: true,
        // 设置定位超时时间，默认：无穷大
        timeout: 10000,
        ...options
      })
      geolocation.getCurrentPosition()
      AMap.event.addListener(geolocation, 'complete', (data) => {
        resolve(data)
      })
      AMap.event.addListener(geolocation, 'error', (error) => {
        reject(error)
      })
    })
  })
}

export const autoComplete = (() => {
  let complete = ''
  return (keyword) => {
    return new Promise((resolve, reject) => {
      function initComplete () {
        AMap.plugin('AMap.Autocomplete', function() {
          // 实例化Autocomplete
          var autoOptions = {
            // city 限定城市，默认全国
            city: '全国'
          }
          complete = new AMap.Autocomplete(autoOptions)
          complete.search(keyword, function(status, result) {
            // 搜索成功时，result即是对应的匹配数据
            resolve(result, status)
          })
        })
      }
      if (complete) {
        complete.search(keyword, function(status, result) {
          // 搜索成功时，result即是对应的匹配数据
          resolve(result, status)
        })
      } else {
        initComplete()
      }
    })
  }
})()
